package com.itheima.sh.web;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.处理请求乱码
        request.setCharacterEncoding("utf-8");
        //2.获取请求参数
        /*
            username: zhansgan
            pwd: 123

            下面的代码request.getParameter("username");的参数书写什么看前端抓包后冒号左边的内容
         */
        String username = request.getParameter("username");
        String password = request.getParameter("pwd");
        String inputCode = request.getParameter("checkcode");

        //request.getSession().setAttribute("checkcode", sb.toString());
        String sessionCheckCode = (String) request.getSession().getAttribute("checkcode");
        //3.创建User对象
        User user = new User();
        //4.将请求参数封装到User对象中
        user.setUsername(username);
        user.setPassword(password);
        response.setContentType("text/html;charset=utf-8");
        if (sessionCheckCode.equalsIgnoreCase(inputCode)){
            //5.创建service业务层对象
            UserServiceImpl userServiceImpl = new UserServiceImpl();
            //6.使用业务层对象调用业务层的登录方法将User对象传递到业务层
            User u = userServiceImpl.login(user);
            //7.判断返回值u是否等于null
            if (u == null){
                //8.如果等于null，说明用户名或者密码错误，响应给前端false
                response.getWriter().print(false);
            }else{
                //9.如果不等于null，说明登录成功，响应给前端true
                response.getWriter().print(true);
            }
        }else{
            response.getWriter().print(false);
        }

    }
}
